<script setup>


import {createVNode, onMounted, ref} from "vue";
import ajax from "@/main.js";
import {Modal, notification} from "ant-design-vue";
import {ExclamationCircleOutlined, QuestionCircleOutlined} from "@ant-design/icons-vue";

const formState = ref({
  taskName: ''
})

function searchServer() {
  ajax.get('/demo/taskManage/searchTask?taskName=' + formState.value.taskName).then(res => {
    if (res.data.code === 200) {
      dataNew.value = res.data.data
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  })
}

const columns = [
  {
    title: '任务名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '服务器名称',
    dataIndex: 'servername',
    key: 'servername',
  },
  {
    title: '任务时间',
    key: 'timelist',
    dataIndex: 'timelist',
  },
  {
    title: '创建时间',
    key: 'time',
    dataIndex: 'time',
  },
  {
    title: '操作',
    key: 'action',
  },
];

const dataNew = ref([{
  taskName: 'aaa',
  timeList: ['00:00', '01:00'],
  servername: 'serv',
  updatetime: '2024-08-06 12:23:22',
  id: 0
}])

function formatDateTime(dateTimeStr) {
  // 假设dateTimeStr的格式为 "YYYY-MM-DDTHH:mm:ss.sss+00:00"
  // 首先，移除时间字符串中的 "T" 和时区信息
  let dateTimeWithoutTZ = dateTimeStr.replace('T', ' ').replace(/\+\d{2}:\d{2}$/, '');

  // 分离日期和时间
  let [date, time] = dateTimeWithoutTZ.split(' ');

  // 将时间转换为小时、分钟和秒
  let [hours, minutes, seconds] = time.split(':').map(Number);

  // 加上8小时（这里不考虑夏令时或更复杂的时区转换）
  hours = (hours + 8) % 24; // 处理超过24小时的情况

  // 重新组合时间字符串
  let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

  // 返回最终格式化的日期时间字符串
  return `${date} ${formattedTime}`;
}

// 删除任务
function delTask(id) {
  Modal.confirm({
    title: '确认删除任务？',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
        'div',
        {
          style: 'color:red;',
        },
        '删除任务后，任务将不占用服务器资源，无法恢复！',
    ),
    onOk() {
      ajax.post('/demo/taskManage/delTask', {'id': id}).then(res => {
        if (res.data.code === 200) {
          getTaskInfo();
        } else {
          notification['error']({
            message: '错误提示',
            description: res.data.msg,
          });
        }
      })
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });


}

// 获取任务信息
function getTaskInfo() {
  ajax.get('/demo/taskManage/taskInfo').then(res => {
    if (res.data.code === 200) {
      dataNew.value = res.data.data
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  })
}

onMounted(() => {
  getTaskInfo();
})

function editTask(id) {
  open2.value = true;
  spinning.value = true;
  // 获取任务信息
  ajax.get('/demo/taskManage/taskDetail?id=' + id).then(res => {
    if (res.data.code === 200) {
      formTask.value = res.data.data
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  });

// 获取可选服务器
  ajax.get('/demo/taskManage/serverAvailable').then(res => {
    if (res.data.code === 200) {
      formTask.value.serverOptions = []
      formTask.value.serverOptions = res.data.data
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  })

  spinning.value = false;
}

const open2 = ref(false);

function onClose2() {
  open2.value = false;
}

const formTask = ref({
  id: 0,
  sid: 0,
  taskName: '',
  servername: '',
  timeList: [],
  options: [],
  serverOptions: []
})

function subEditTask() {
  if (formTask.value.taskName.length === 0 || formTask.value.timeList.length === 0) {
    notification['error']({
      message: '错误提示',
      description: '未输入任务名称或未选择时间段',
    });
  } else {
    ajax.post('/demo/taskManage/subEditTask', formTask.value).then(res => {
      if (res.data.code === 200) {
        open2.value = false;
        getTaskInfo();
      } else {
        notification['error']({
          message: '错误提示',
          description: res.data.msg,
        });
      }
    })
  }
}

function handleChange(value, option) {
  if(formTask.value.sid !== value){
    formTask.value.timeList = [];
  }
  formTask.value.servername = option.label;
  formTask.value.sid = option.value;
  spinning.value = true;
  ajax.get('/demo/taskManage/serverTime?id=' + value).then(res => {
        if (res.data.code === 200) {
          formTask.value.options = res.data.data;
        } else {
          notification['error']({
            message: '错误提示',
            description: res.data.msg,
          });
        }
      }
  )
  spinning.value = false;
}


const spinning = ref(false);

</script>

<template>
  <!--search-->
  <a-flex>
    <div class="know-add">
    </div>
    <div class="know-search">
      <a-form
          :model="formState"
          name="horizontal_login"
          layout="inline"
          autocomplete="off"
      >
        <a-form-item
            label="任务名称"
            name="taskName"
            :rules="[{ required: true, message: '' }]"
        >
          <a-input v-model:value="formState.taskName" placeholder="请输入任务名称" style="width: 100%;"/>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" @click="searchServer">查询</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-flex>

  <!--table-->
  <a-table :columns="columns" :data-source="dataNew" style="margin-top: 20px;">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'name'">
        <a>{{ record.taskName }}</a>
      </template>
      <template v-else-if="column.key === 'servername'">
        {{ record.servername }}
      </template>
      <template v-else-if="column.key === 'timelist'">
        <span>
          <a-tag
              v-for="tag in record.timeList"
              :key="tag"
              color="#2db7f5"
          >
            {{ tag }}
          </a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'time'">
        <span>
          {{ formatDateTime(record.updatetime) }}
        </span>
      </template>
      <template v-else-if="column.key === 'action'">
        <span>
          <a-divider type="vertical"/>
          <a @click="delTask(record.id)">删除</a>
          <a-divider type="vertical"/>
          <a @click="editTask(record.id)">编辑</a>
        </span>
      </template>
    </template>
  </a-table>


  <!--  编辑任务-->

  <a-drawer
      title="编辑任务"
      :width="720"
      :open="open2"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose2"
  >
    <a-spin :spinning="spinning">
      <a-form :model="formTask" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="18">
            <a-form-item label="任务名称" name="name" :rules="[{ required: true, message: '' }]">
              <a-input v-model:value="formTask.taskName" placeholder="请输入任务名称"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="18">
            <a-form-item label="服务器名称" name="servername" :rules="[{ required: true, message: '' }]">
              <a-select

                  v-model:value="formTask.servername"
                  @change="handleChange"
                  placeholder="请输入服务器名称"
                  :options="formTask.serverOptions"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="18">
            <a-form-item name="time" :rules="[{ required: true, message: '' }]">
              <template #label>任务时段选择
                <a-popover title="时间段说明">
                  <template #content>
                    <p>时间每半小时被划分为一个时间段</p>
                    <p>比如12:00指12:00-12:30这段时间</p>
                  </template>
                  <QuestionCircleOutlined/>
                </a-popover>
              </template>

              <a-select
                  v-model:value="formTask.timeList"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="请选择时间段"
                  :options="formTask.options"
              ></a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <template #extra>
      <a-space>
        <a-button @click="onClose2">取消</a-button>
        <a-button type="primary" @click="subEditTask">更新</a-button>
      </a-space>
    </template>
  </a-drawer>

</template>

<style scoped>
.know-add {
  width: 70%;
}

.know-search {
  width: 30%;
}
</style>